package direct;

import com.rabbitmq.client.*;
import util.Tools;

/**
 * 描述：接收ERROR级别的日志消息
 */

public class RecvLogsDirect2 {
    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = Tools.getFactory();
        Connection connection = factory.newConnection();
        connection.createChannel();
        // 声明一个direct类型的交换机
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        // 声明一个随机临时队列，该队列会在使用完后自动销毁
        String queueName = channel.queueDeclare().getQueue();
        // 将队列绑定到交换机上，绑定一个路由键，接收ERROR级别的日志消息
        channel.queueBind(queueName, EXCHANGE_NAME, "error");

        System.out.println("开始接收消息，等级为error，退出请按 CTRL+C");
        // 创建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 消息到达时会调用此方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body);
                System.out.println("接收消息，路由键为：'" + envelope.getRoutingKey() + "'，内容为：'" + message + "'");
            }
        };
        // 消费消息
        channel.basicConsume(queueName, true, consumer);
    }
}
